package 链表;

/**
 * https://leetcode-cn.com/problems/merge-two-sorted-lists/
 * @author 会玩的洋洋
 *
 */
public class _21_合并两个有序链表 {
	
	/**
	 * @param l1
	 * @param l2
	 * @return
	 */
	public ListNode mergeTwoLists2(ListNode l1, ListNode l2) {
		ListNode prehead = new ListNode(-1);

        ListNode prev = prehead;
        while (l1 != null && l2 != null) {
            if (l1.val <= l2.val) {
                prev.next = l1;
                l1 = l1.next;
            } else {
                prev.next = l2;
                l2 = l2.next;
            }
            prev = prev.next;
        }

        // 合并后 l1 和 l2 最多只有一个还未被合并完，我们直接将链表末尾指向未合并完的链表即可
        prev.next = l1 == null ? l2 : l1;

        return prehead.next;
	}
	
	/**
	 * @param l1
	 * @param l2
	 * @return
	 */
	public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
		if (l1 == null && l2 == null) {
			return null;
		}
		ListNode ans = new ListNode();
		ListNode cur = ans;
		while (l1 != null && l2 != null) {
			cur.val = l1.val > l2.val ? l2.val : l1.val;
            cur.next = new ListNode();
			cur = cur.next;
			if (l1.val > l2.val) {
				l2 = l2.next;
			}else {
				l1 = l1.next;
			}
		}
		if (l1 != null) {
			cur.val = l1.val;
			cur.next = l1.next;
		}else if (l2 != null) {
			cur.val = l2.val;
			cur.next = l2.next;
		}
		return ans;
    }
}
